/**
 * 文章模块控制文件
 * @type {exports|*}
 */

var mongoose = require('mongoose')
  , Article = mongoose.model('Article');

/**
 * 首页
 * @param req
 * @param res
 */
exports.index = function(req, res) {
  res.render('article/index', {});
}

/**
 * 编辑文章
 * @param req
 * @param res
 */
exports.edit = function(req, res){
  var id = req.params.id;
  Article.load(id, function (err, article) {
    if (err || !article) {
      res.send('not found');
      return err;
    }
    res.render('article/load_article', {title : '编辑文章', article : article});
  })
}

/**
 * 查看文章
 * @param req
 * @param res
 */
exports.load = function(req, res){
  var id = req.params.id;
  console.log(req.query);
  Article.load(id, function (err, article) {
    if (err || !article) {
      res.send('not found');
      return err;
    }
    res.render('article/article', {title : article.title, article : article});
  })
}

/**
 * 更新文章
 * @param req
 * @param res
 */
exports.update = function(req, res) {
  Article.update({ _id: req.body.id}, req.body, function(err, numberAffect) {
    if (err) {
      res.json({msg : '保存失败'});
      return;
    }
    numberAffect && res.json({success : 1});
  });
}

/**
 * 添加文章
 * @param req
 * @param res
 */
exports.addArticle = function(req, res){
  var article = new Article(req.body);

  article.save(function(err){
    if (err) res.json(err.errors.body)
    else res.json({success : 1});
  });
};

/**
 * 添加文章界面
 * @param req
 * @param res
 */
exports.addArticleShow = function(req, res) {
  var render = {
    title : "文章添加",
    article : new Article({})
  };

  res.render('article/add_article', render);
};

/**
 * 删除文章
 * @param req
 * @param res
 */
exports.deleteArticle = function(req, res) {
  Article.load(req.params.id, function(err, article) {
    article.remove(function(err) {
      if(err) return res.send({ success: false, message: err.message })
      res.send('done');
    });
  })
}

/**
 * 文章列表
 * @param req
 * @param res
 */
exports.articleList = function(req, res) {
  var page = (req.param('page') > 0 ? req.param('page') : 1) - 1
    , perPage = 4
    , render = {
      title : "文章列表"
    }
    , options = {
      perPage : perPage,
      page : page
    };

  //读取文章
  Article.list(options, function(err, list){
    render.articleList = list;
    Article.count().exec(function(err, count) {
      if(err) console.log(err);
      render.page = page +1;
      render.pages = Math.ceil(count/perPage);
      render.count = count;
      if((page+1)>render.pages) res.redirect('/article/list/'+render.pages+'.html');
      res.render('article/article_list', render);
    });
  });
};